package com.example.datn.fragments;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.example.datn.R;
import com.example.datn.activities.PlayMediaActivity;
import com.example.datn.activities.SongsViewActivity;
import com.example.datn.adapter.SongItemAdapter;
import com.example.datn.customviews.MusicBarButton;
import com.example.datn.manager.ResourceManager;
import com.example.datn.manager.SongManager;
import com.example.datn.manager.UrlManager;
import com.example.datn.objects.SongObject;

import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class SongsFragment extends Fragment implements OnClickListener, OnCompletionListener{

	private ListView lv_listSong;
	private View rootView;
	private TextView tv_status_connection, tv_songName_musicBar;
	private SongItemAdapter adapter=null;
	private MusicBarButton musicBar;
	private MediaPlayer mediaPlayer;
	private ImageButton btn_play_pause_mbar, btn_previous_mbar, btn_next_mbar;
	boolean isLoading = false;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {		
		rootView = inflater.inflate(R.layout.list_songs, container, false);
			
		initView();
				
		//hien thi thong bao khong co ket noi mang		
		if(!ResourceManager.hasConnection)
			tv_status_connection.setVisibility(View.VISIBLE);
		else
			tv_status_connection.setVisibility(View.GONE);
		
		//add list vao listView
    	ArrayList<SongObject> listAllSong = SongManager.getInstance().getListSong();        		
		adapter = new SongItemAdapter(getActivity(), R.layout.my_song_item, listAllSong);
		lv_listSong.setAdapter(adapter);  
		lv_listSong.setOnItemClickListener(listItemClick);
				
		musicBar = new MusicBarButton(inflater.getContext(), R.id.music_bar, rootView);		
		musicBar.setOnClickListener(this);	
	
		mediaPlayer = SongManager.getInstance().getCurrentMediaPlayer();				
		if(mediaPlayer != null){
			mediaPlayer.setOnCompletionListener(this);
			SongObject song = SongManager.getInstance().getCurrentSong();
			if(mediaPlayer.isPlaying())
				btn_play_pause_mbar.setImageResource(R.drawable.media_play_img);
			else {
				btn_play_pause_mbar.setImageResource(R.drawable.media_pause_img);
			}
			musicBar.setVisibility(View.VISIBLE);
			tv_songName_musicBar.setText(song.songName);
			btn_next_mbar.setVisibility(View.VISIBLE);
			btn_previous_mbar.setVisibility(View.VISIBLE);
		}
		else{
			musicBar.setVisibility(View.GONE);
			btn_play_pause_mbar.setImageResource(R.drawable.media_play_img);
			btn_play_pause_mbar.setVisibility(View.GONE);			
		}
				
		return rootView;
	}
	
	private void initView() {
		tv_status_connection = (TextView)rootView.findViewById(R.id.tv_status_connect_listsong);
		tv_songName_musicBar = (TextView)rootView.findViewById(R.id.tv_song_name_musicBar);
		tv_songName_musicBar.setOnClickListener(this);
		
		lv_listSong = (ListView)rootView.findViewById(R.id.lv_list_song);
		
		btn_next_mbar = (ImageButton)rootView.findViewById(R.id.ibtn_next_musicBar);
		btn_play_pause_mbar = (ImageButton)rootView.findViewById(R.id.ibtn_pause_musicBar);		
		btn_play_pause_mbar.setOnClickListener(this);
		
		btn_previous_mbar = (ImageButton)rootView.findViewById(R.id.ibtn_back_musicBar);
		btn_previous_mbar.setOnClickListener(this);
		btn_next_mbar = (ImageButton)rootView.findViewById(R.id.ibtn_next_musicBar);
		btn_next_mbar.setOnClickListener(this);
	}

	
	
	//bat su kien click vao item song in list 
	OnItemClickListener listItemClick = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int id,
				long arg3) {					
			if(!isLoading){
				SongObject song = SongManager.getInstance().getListSong().get(id);
				Toast.makeText(getActivity(), 
						"song: "+ song.songName, 
						Toast.LENGTH_SHORT).show();	
				
				SongManager.getInstance().setCurrentSong(song);
				
				musicBar.setVisibility(View.VISIBLE);
				mediaPlayer = SongManager.getInstance().getCurrentMediaPlayer();
//				if(mediaPlayer != null && mediaPlayer.isPlaying())
//					SongManager.getInstance().getCurrentMediaPlayer().stop();
				try {				
					if(song.linkAudio == null || song.linkAudio == "")
						new getLinkAudioTask().execute(song);
					else
						playMedia(song.urlSong, mediaPlayer);
						//new LoadMediaTask().execute(song.urlSong);
				} catch (Exception e) {
					Log.d("error load media", "can't load song - error - " + e.toString());
				}  							
			}
			
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_song_name_musicBar:
		case R.id.music_bar:
			Intent i = new Intent(getActivity(), PlayMediaActivity.class);	
			getActivity().finish();
			startActivity(i);			
			break;

		case R.id.ibtn_pause_musicBar:
			MediaPlayer media = SongManager.getInstance().getCurrentMediaPlayer();
			if(media != null){
				if(media.isPlaying()){
					media.pause();
					btn_play_pause_mbar.setImageResource(R.drawable.media_pause_img);
				}
				else{
					media.start();
					btn_play_pause_mbar.setImageResource(R.drawable.media_play_img);
				}
			}	
			break;
			
		case R.id.ibtn_next_musicBar:
			nextSong();
			break;
			
		case R.id.ibtn_back_musicBar:
			previousSong();
			break;
		}
	}
			
	private void nextSong() {
		SongObject song = SongManager.getNextSong();
		SongManager.getInstance().setCurrentSong(song);		
		try {
			if(song.linkAudio == null || song.linkAudio == "")
				new getLinkAudioTask().execute(song);
			else
				playMedia(song.urlSong, mediaPlayer);
				//new LoadMediaTask().execute(song.linkAudio);
		} catch (Exception e) {
			Log.d("error load media", "can't next song - error - " + e.toString());
		} 
	}
	
	private void previousSong(){
		SongObject song = SongManager.getPreviousSong();
		SongManager.getInstance().setCurrentSong(song);
		try {
			if(song.linkAudio == null || song.linkAudio == "")
				new getLinkAudioTask().execute(song);
			else
				playMedia(song.urlSong, mediaPlayer);
				//new LoadMediaTask().execute(song.linkAudio);
		} catch (Exception e) {
			Log.d("error load media", "can't previous song - error - " + e.toString());
		} 
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	
    @Override
	public void onCompletion(MediaPlayer mp) {
    	nextSong();
	}
    
    //asynctask de load link audio
    private class getLinkAudioTask extends AsyncTask<SongObject, Void, Void>{
    	SongObject song;
    	String link = "";
    	
    	@Override
		protected void onPreExecute() {
    		isLoading = true;
			tv_songName_musicBar.setText("loading ... ");
			tv_songName_musicBar.setEnabled(false);			
			musicBar.setEnabled(false);
			btn_next_mbar.setVisibility(View.GONE);
			btn_play_pause_mbar.setVisibility(View.GONE);
			btn_previous_mbar.setVisibility(View.GONE);
			super.onPreExecute();
		}
    	
		@Override
		protected Void doInBackground(SongObject... params) {			
			try {			
				Document doc;						
				song = params[0];
				doc = Jsoup.connect(song.urlSong).get();
				Jsoup.connect(song.urlSong).timeout(5000).ignoreHttpErrors(true);
				String a = doc.toString(),b;								
				Pattern pattern = Pattern.compile("xmlURL=([^&]*)");
				Matcher matcher = pattern.matcher(a);
				if (matcher.find()){
				    b = matcher.group(1);			    			   
				    doc = Jsoup.connect(b).get();				
					pattern = Pattern.compile("</source>(.+?)=");
					matcher = pattern.matcher(doc.toString());
					if (matcher.find()){
						link = matcher.group(1);
					}
				}				
			} catch (IOException e) {
				e.printStackTrace();
				Log.d("loi", "loi load link - " + e.toString());
			}		
			
			song.linkAudio = link;
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {			
			super.onPostExecute(result);			
			if(song.linkAudio != "")
				playMedia(song.linkAudio, mediaPlayer);
				//new LoadMediaTask().execute(song.linkAudio);
		}    		
    }
    
    
  //chay media tu url
  	private void playMedia(String url, MediaPlayer media){  		
  		tv_songName_musicBar.setText("loading ... ");
		tv_songName_musicBar.setEnabled(false);			
		musicBar.setEnabled(false);
		btn_next_mbar.setVisibility(View.GONE);
		btn_play_pause_mbar.setVisibility(View.GONE);
		btn_previous_mbar.setVisibility(View.GONE);
		
  		//SongManager.killMediaPlayer(mediaPlayer);
		
		if(media == null){
			media = new MediaPlayer();			
		}	
		else if(media.isPlaying()){
			media.stop();			
		}
		media.reset();        
        try {
        	media.setDataSource(url);
        	media.prepare();
  		} catch (Exception e) {
  			e.printStackTrace();
  		} 			
          
        media.start();					
        media.setOnCompletionListener(this);
  		SongManager.getInstance().setCurrentMediaPlayer(media);	
  		
  		tv_songName_musicBar.setText(
				SongManager.getInstance().getCurrentSong().songName);
		tv_songName_musicBar.setEnabled(true);
		musicBar.setEnabled(true);		
		btn_play_pause_mbar.setVisibility(View.VISIBLE);
		btn_play_pause_mbar.setImageResource(R.drawable.media_play_img);
		btn_next_mbar.setVisibility(View.VISIBLE);
		btn_previous_mbar.setVisibility(View.VISIBLE);
		
		isLoading = false;
  	}     
}
